package cn.luyou.admin.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import cn.luyou.admin.common.JwtUtils;
import cn.luyou.admin.utils.BaseContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("JwtInterceptor.preHandle()");
        // Skip OPTIONS requests
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // Get token from header
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        // Remove "Bearer " prefix
        token = token.substring(7);

        // Validate token
        if (!jwtUtils.validateToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        try {
            // Get user info from token
            String username = jwtUtils.getUsernameFromToken(token);
            String role = jwtUtils.getRoleFromToken(token);
            Long userId = jwtUtils.getUserIdFromToken(token);
            System.out.println("UserId: " + userId);
            // Store in request attributes
            request.setAttribute("username", username);
            request.setAttribute("role", role);
            request.setAttribute("userId", userId);

            // Store userId in BaseContext
            BaseContext.setCurrentId(userId);
            System.out.println("UserId stored in BaseContext: " + userId);

            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // Clear ThreadLocal after request is completed
        BaseContext.remove();
    }
} 